package cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.application;

import cn.caplike.demo.rabbitmq.springboot.idempotence_reliability.common.domain.model.MailRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Base64;

/**
 * Description: 定时邮件重发服务
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-09-02 21:56
 */
@Slf4j
@Service
public class ScheduledMailResendingService {

    private MessageDeliveryLogService messageDeliveryLogService;

    private RabbitTemplate rabbitTemplate;

    /**
     * Description: 每隔一定时间 (30s) 抓取投递失败的消息执行重新投递
     *
     * @return void
     * @author LiKe
     * @date 2020-09-03 09:45:17
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void execute() {
        log.info("Producer :: 开始执行定时任务 - 重新投递");

        messageDeliveryLogService.fetchDeliveryFailed().forEach(messageDeliveryLog -> {
            final String messageId = messageDeliveryLog.getMessageId();
            if (messageDeliveryLog.getRetryCount() <= 3) {
                rabbitTemplate.convertAndSend(
                        messageDeliveryLog.getExchange(),
                        messageDeliveryLog.getRoutingKey(),
                        JSON.parseObject(new String(Base64.getDecoder().decode(messageDeliveryLog.getMessage().getBytes())), MailRequest.class),
                        new CorrelationData(messageId)
                );

                messageDeliveryLogService.updateResendingStatus(messageId);
                log.info("Producer :: 第 {} 次重新投递消息 (messageId: {})", messageDeliveryLog.getRetryCount() + 1, messageId);
            }
            log.error("Producer :: 消息 (messageId: {}) 超过重试次数", messageId);
        });
    }

    // ~ Autowired
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    public void setMessageDeliveryLogService(MessageDeliveryLogService messageDeliveryLogService) {
        this.messageDeliveryLogService = messageDeliveryLogService;
    }

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }
}
